package com.test.demo.service.impl;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.test.demo.config.DynamicDataSource;
import com.test.demo.entity.e.DataSourceProperties;
import com.test.demo.mapper.DataSourceConfigMapper;
import com.test.demo.service.DataSourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

@Service
public class DataSourceServiceImpl extends ServiceImpl<DataSourceConfigMapper, DataSourceProperties> implements DataSourceService {

    @Autowired
    private DynamicDataSource dynamicDataSource;

    @Override
    public List<DataSourceProperties> getAllEnabledDataSources() {
        return list(new LambdaQueryWrapper<DataSourceProperties>()
                .eq(DataSourceProperties::getStatus, 1));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addDataSource(DataSourceProperties properties) {
        // 测试数据源连接
        if (!testConnection(properties)) {
            throw new RuntimeException("数据源连接测试失败");
        }

        // 保存配置到数据库
        if (!save(properties)) {
            throw new RuntimeException("保存数据源配置失败");
        }

        // 创建数据源并添加到动态数据源中
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(properties.getDriverClassName());
        dataSource.setUrl(properties.getUrl());
        dataSource.setUsername(properties.getUsername());
        dataSource.setPassword(properties.getPassword());
        // 设置其他连接池属性
        dataSource.setInitialSize(5);
        dataSource.setMinIdle(10);
        dataSource.setMaxActive(20);

        try {
            dynamicDataSource.addDataSource(properties.getDatasourceKey(), dataSource);
            return true;
        } catch (Exception e) {
            throw new RuntimeException("添加数据源失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeDataSource(String key) {
        // 从数据库中删除配置
        remove(new LambdaQueryWrapper<DataSourceProperties>()
                .eq(DataSourceProperties::getDatasourceKey, key));
        
        // 从动态数据源中移除
        try {
            dynamicDataSource.removeDataSource(key);
            return true;
        } catch (Exception e) {
            throw new RuntimeException("删除数据源失败", e);
        }
    }

    @Override
    public boolean testConnection(DataSourceProperties properties) {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(properties.getDriverClassName());
        dataSource.setUrl(properties.getUrl());
        dataSource.setUsername(properties.getUsername());
        dataSource.setPassword(properties.getPassword());

        try (Connection conn = dataSource.getConnection()) {
            return true;
        } catch (SQLException e) {
            return false;
        } finally {
            dataSource.close();
        }
    }
} 